﻿using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using Newtonsoft.Json.Linq;

namespace ConsoleAppPrj
{
    internal class Program
    {
        static async Task Main01(string[] args)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://192.168.2.69:5000/");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "a3facbaa8ddb30b76cad6e4a8e445d0d57e840095bc24017fef8e6300bc9747d");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

                using (var content = new MultipartFormDataContent())
                {
                    byte[] fileContent = System.IO.File.ReadAllBytes("E:/tmpfile/1.jpg");
                    var fileStreamContent = new ByteArrayContent(fileContent);
                    fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    content.Add(fileStreamContent, "file", Path.GetFileName("E:/tmpfile/1.jpg"));
                    // content.Add(new StringContent("2023-10-05T14:48:00Z"), "timestamp");

                    HttpResponseMessage response = client.PostAsync("/api/meter/reading", content).Result;

                    string responseBody = response.Content.ReadAsStringAsync().Result;


                    JArray jsonArray = JArray.Parse(responseBody);
                    int reading = Convert.ToInt32(jsonArray[0]["reading"]);
                    Console.WriteLine(responseBody);
                }
            }
        }


        private static Program instance = new Program();

        private Program() { }

        public static Program GetInstance()
        {
            return instance;
        }

        private string SendPostRequest(string jsonRequestString, string restServiceURL)
        {
            string jsonResponseStr = null;
            try
            {
                HttpWebRequest httpConnection = (HttpWebRequest)WebRequest.Create(restServiceURL);
                httpConnection.Method = "POST";
                httpConnection.ContentType = "application/json;charset=UTF-8";

                byte[] requestBytes = Encoding.UTF8.GetBytes(jsonRequestString);
                httpConnection.ContentLength = requestBytes.Length;

                using (Stream requestStream = httpConnection.GetRequestStream())
                {
                    requestStream.Write(requestBytes, 0, requestBytes.Length);
                }

                using (HttpWebResponse response = (HttpWebResponse)httpConnection.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception($"Failed : HTTP error code : {response.StatusCode}");
                    }

                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        jsonResponseStr = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return jsonResponseStr;
        }

        private string EncoderByMd5(string str)
        {
            try
            {
                MD5 md5 = MD5.Create();
                byte[] inputBytes = Encoding.UTF8.GetBytes(str);
                byte[] hashBytes = md5.ComputeHash(inputBytes);
                return Convert.ToBase64String(hashBytes);
            }
            catch (Exception)
            {
                return "";
            }
        }


        static async Task Main(string[] args)
        {
            Program client = Program.GetInstance();
            string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string user = "user";
            string siid = "";
            string secretKey = "secretKey";
            string transactionID = timeStamp;
            string streamingNo = siid + transactionID;
            string authenticator = client.EncoderByMd5(timeStamp + transactionID + streamingNo + secretKey);
            string mobile = "mobile";
            string content = "content";
            string url = "url";

            string req = $"{{\"siid\":\"{siid}\",\"user\":\"{user}\", \"streamingNo\":\"{streamingNo}\"" +
                        $",\"timeStamp\":\"{timeStamp}\",\"transactionID\":\"{transactionID}\"" +
                        $",\"authenticator\":\"{authenticator}\",\"mobile\":\"{mobile}\"" +
                        $",\"content\":\"{content}\"}}";

            Console.WriteLine(req);
            string ret = instance.SendPostRequest(req, url);
            Console.WriteLine(ret);
        }
    }
}
